package com.simple.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.simple.common.constant.ProductConstant;
import com.simple.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.simple.gulimall.product.dao.AttrGroupDao;
import com.simple.gulimall.product.dao.CategoryDao;
import com.simple.gulimall.product.entity.*;
import com.simple.gulimall.product.service.CategoryService;
import com.simple.gulimall.product.vo.AttrRespVo;
import com.simple.gulimall.product.vo.AttrVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.simple.common.utils.PageUtils;
import com.simple.common.utils.Query;

import com.simple.gulimall.product.dao.AttrDao;
import com.simple.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Resource
    AttrAttrgroupRelationDao relationDao;
    @Resource
    CategoryDao categoryDao;
    @Resource
    AttrGroupDao attrGroupDao;
    @Resource
    CategoryService categoryService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {
        //1、保存基本信息
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        this.save(attrEntity);
        // 如果是基本属性，才会有关联关系
        if (attr.getAttrType()== ProductConstant.AttrTypeEnum.ATTR_TYPE_BASE.getCode()&&attr.getAttrGroupId()!=null){
            //2、保存关联关系
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrId(attrEntity.getAttrId());
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationDao.insert(relationEntity);
        }

    }

    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String attrType) {

        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("attr_type","base".equalsIgnoreCase(attrType)? ProductConstant.AttrTypeEnum.ATTR_TYPE_BASE.getCode() : ProductConstant.AttrTypeEnum.ATTR_TYPE_SALE.getCode());
        String key = (String) params.get("key");
        // 基础查询
        // 如果等于0代表查询全部
        // 不等于0代表根据catelog_id查询
        if (catelogId!=0){
            queryWrapper.eq("catelog_id",catelogId);
        }
        // 如果传入的params中的key不为空，代表有关键字查询
        if (!StringUtils.isEmpty(key)){
            queryWrapper.and((wrapper)->{
                // 关键字可以是attr_id或者模糊匹配attr_name
                wrapper.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), queryWrapper);
        PageUtils pageUtils = new PageUtils(page);
        // 查询出所需要的catelogName和groupName
        List<AttrEntity> records = page.getRecords();
        List<AttrRespVo> respVos = records.stream().map((attrEntity) -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity, attrRespVo);
//            System.out.println("attrRespVo:"+attrRespVo);
            if (attrRespVo.getAttrType()== ProductConstant.AttrTypeEnum.ATTR_TYPE_BASE.getCode()) {
                // 根据attr_id从AttrAttrgroupRelationDao中查询出attr_group_id
                // 注意这里不能用selectById 因为这个attr_id并不是该表的主键，该表有一个主键id
                Long attrId = attrRespVo.getAttrId();
                if (attrId!=null){
                    AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attrId ));
                    if (relationEntity!=null){
                        Long attrGroupId = relationEntity.getAttrGroupId();
//                System.out.println("relationEntity"+relationEntity);
                        if (attrGroupId != null) {
                            //根据attr_group_id从AttrGroupDao中查询出attr_group_name
                            AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrGroupId);
//                    System.out.println("attrGroupEntity"+attrGroupEntity);
                            attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                        }
                    }

                }

            }
            //根据catelogId从CategoryDao中查询出categoryName
            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            if (categoryEntity != null) {
                attrRespVo.setCatelogName(categoryEntity.getName());
            }

            return attrRespVo;
        }).collect(Collectors.toList());

        pageUtils.setList(respVos);

        return pageUtils;
    }

    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrRespVo attrRespVo = new AttrRespVo();
        // 将基本属性获取到
        AttrEntity attrEntity = this.getById(attrId);
        BeanUtils.copyProperties(attrEntity,attrRespVo);
        // attrGroupId、valueType和catelogPath需要获取

        // 如果是基本属性，才去获取分组信息
        if (attrEntity.getAttrType()== ProductConstant.AttrTypeEnum.ATTR_TYPE_BASE.getCode()){
            // attrGroupId
            AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            if (relationEntity!=null){
                attrRespVo.setAttrGroupId(relationEntity.getAttrGroupId());
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                // attrGroupName
                if (attrGroupEntity!=null){
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }

        // valueType: 如果value_select中有分号，代表不止一个值，valueType就等于1
        // 如果去除;字符串后与原字符串相同，就代表无;,即仅有1个值，valueType就等于0
        if (attrEntity.getValueSelect().replace(";", "").equals(attrEntity.getValueSelect())){
            attrRespVo.setValueType(0);
        }else {
            attrRespVo.setValueType(1);
        }

        // catelogPath
        Long catelogId = attrRespVo.getCatelogId();
        Long[] catelogPath = categoryService.findCatelogPath(catelogId);
        CategoryEntity categoryEntity = categoryService.getById(catelogId);
        // catelogName
        if (categoryEntity!=null){
            attrRespVo.setCatelogName(categoryEntity.getName());
        }
        attrRespVo.setCatelogPath(catelogPath);

        return attrRespVo;
    }

    @Transactional
    @Override
    public void updateAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        // 如果是基本属性，才去修改
        if (attrEntity.getAttrType()== ProductConstant.AttrTypeEnum.ATTR_TYPE_BASE.getCode()){
            //修改基本属性
            this.updateById(attrEntity);
            if (attr.getAttrGroupId()!=null) {
                //根据attrId修改attrGroupRelation关联信息表中的attrGroupId
                AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
                attrAttrgroupRelationEntity.setAttrId(attr.getAttrId());
                attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
                // 判断表中attr_id对应的是否有attrGroupId，如果有，则是更新，如果没有，就是新增
                Integer count = relationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrAttrgroupRelationEntity.getAttrId()));
                if (count > 0) {
                    relationDao.update(attrAttrgroupRelationEntity, new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrAttrgroupRelationEntity.getAttrId()));
                } else {
                    relationDao.insert(attrAttrgroupRelationEntity);
                }
            }
        }

    }

    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        List<AttrAttrgroupRelationEntity> relationEntities = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));

        List<Long> attrIds = relationEntities.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());

        if (attrIds.isEmpty()||attrIds.size()==0)
            return null;
        return this.listByIds(attrIds);
    }

    //查询出所有该attrgroup所属分类下没有被关联的attr
    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrgroupId) {
        //1、获取对应的categoryId
        AttrGroupEntity groupEntity = attrGroupDao.selectById(attrgroupId);
        Long catelogId = groupEntity.getCatelogId();
        //2、获取该分类下所有没有被关联了的属性
        //2.1 该分类下所有其他分组
        List<AttrGroupEntity> attrGroupEntities = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        List<Long> groupIds = attrGroupEntities.stream().map((group) -> {
            return group.getAttrGroupId();
        }).collect(Collectors.toList());

        //2.2 这些其他分组关联的属性
        List<AttrAttrgroupRelationEntity> relationList = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", groupIds));
        List<Long> attrIds = relationList.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());
        //2.3 去除这些其他分组关联的属性
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId).eq("attr_type", ProductConstant.AttrTypeEnum.ATTR_TYPE_BASE.getCode());
        if (!attrIds.isEmpty()){
            queryWrapper.notIn("attr_id", attrIds);
        }
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)){
            queryWrapper.and((wrapper)->{
                wrapper.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = page(new Query<AttrEntity>().getPage(params),queryWrapper);
        PageUtils pageUtils = new PageUtils(page);

        return pageUtils;

    }

    @Override
    public List<AttrEntity> selectSearchAttrs(List<Long> attrIds) {
        return this.list(new QueryWrapper<AttrEntity>().eq("search_type", 1L).in("attr_id", Arrays.asList(attrIds)));

    }


}